{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9efdda2f-e3ab-4ec3-9b04-3ebea6fdf4c1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "import sys\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "import os\n",
    "\n",
    "sys.path.append('../../aisuite')\n",
    "\n",
    "# Load from .env file if available\n",
    "load_dotenv(find_dotenv())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7604862",
   "metadata": {},
   "source": [
    "### Define the function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "aaba7cb2-29de-4552-8fd5-8b966fbc0cd5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def will_it_rain(location: str, time_of_day: str):\n",
    "    \"\"\"Check if it will rain in a location at a given time today.\n",
    "\n",
    "    Args:\n",
    "        location (str): Name of the city\n",
    "        time_of_day (str): Time of the day in HH:MM format.\n",
    "    \"\"\"\n",
    "    return \"YES\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf943639",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "090dc2d1",
   "metadata": {},
   "source": [
    "### Using OpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29537ae1",
   "metadata": {},
   "source": [
    "### JSON spec for the function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b1a7196a-e5f2-4016-8dca-eca804ef18ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [{\n",
    "    \"type\": \"function\",\n",
    "    \"function\": {\n",
    "        \"name\": \"will_it_rain\",\n",
    "        \"description\": \"Check if it will rain in a location at a given time today\",\n",
    "        \"parameters\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {\n",
    "                \"location\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Name of the city\"\n",
    "                },\n",
    "                \"time_of_day\": {\n",
    "                    \"type\": \"string\",\n",
    "                    \"description\": \"Time of the day in HH:MM format.\"\n",
    "                }\n",
    "            },\n",
    "            \"required\": [\"location\", \"time_of_day\"]\n",
    "        }\n",
    "    }\n",
    "}]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5359d145",
   "metadata": {},
   "source": [
    "### Send user request to LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "4b522391-5a82-4d27-bbad-9db91e531815",
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI()\n",
    "messages = [{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"I live in San Francisco. Can you check for weather \"\n",
    "               \"and plan an outdoor picnic for me at 2pm?\"\n",
    "}]\n",
    "response = client.chat.completions.create(\n",
    "    model=\"gpt-4o\", messages=messages, tools=tools\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc47b536",
   "metadata": {},
   "source": [
    "### Process tool call response, Execute the tool & call the model again"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d281fe8e-9d87-4150-be4d-f01a2525edf6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "It looks like it will rain in San Francisco at 2 PM today. It's probably not the best day for an outdoor picnic. Would you like to consider indoor activities or reschedule the picnic for another day?\n"
     ]
    }
   ],
   "source": [
    "response2 = None\n",
    "if response.choices[0].message.tool_calls:\n",
    "    tool_call = response.choices[0].message.tool_calls[0]\n",
    "    args = json.loads(tool_call.function.arguments)\n",
    "\n",
    "    result = will_it_rain(args[\"location\"], args[\"time_of_day\"])\n",
    "    messages.append(response.choices[0].message)\n",
    "    messages.append({\n",
    "        \"role\": \"tool\", \"tool_call_id\": tool_call.id, \"content\": str(result)\n",
    "    })\n",
    "\n",
    "    response2 = client.chat.completions.create(\n",
    "        model=\"gpt-4o\", messages=messages, tools=tools)\n",
    "    print(response2.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e81fb905",
   "metadata": {},
   "source": [
    "### Optionally, continue the conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f6de5c21-2983-4539-a4a2-cdd76071fdea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "If you're set on having the picnic despite the rain, here are a few suggestions to make it enjoyable:\n",
      "\n",
      "1. **Location:** Consider a location with some shelter, like a gazebo in a park, or find a picnic spot with large trees for some natural cover. Alternatively, you might want to think about an indoor space with large windows where you can enjoy the view without getting wet.\n",
      "\n",
      "2. **Packing Essentials:**\n",
      "   - Bring waterproof blankets or tarps to sit on.\n",
      "   - Pack an umbrella or a rain poncho to stay dry.\n",
      "   - Use waterproof containers for your food to keep everything dry.\n",
      "   - Bring extra towels and a change of clothes.\n",
      "\n",
      "3. **Food Ideas:** Opt for warm, hearty meals that are comforting on a rainy day, such as soup in a thermos or grilled sandwiches.\n",
      "\n",
      "4. **Activities:** Plan indoor-friendly games or activities you can enjoy sheltered from the rain, like card games or board games.\n",
      "\n",
      "5. **Safety First:** Check the weather forecast regularly in case of any severe weather warnings.\n",
      "\n",
      "Enjoy your rainy-day picnic!\n"
     ]
    }
   ],
   "source": [
    "messages.append(response2.choices[0].message)\n",
    "messages.append({\n",
    "    \"role\": \"user\", \"content\": \"Schedule it despite the rain\"\n",
    "})\n",
    "response = client.chat.completions.create(\n",
    "    model=\"gpt-4o\", messages=messages)\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6d5fd91",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "897b9aa2",
   "metadata": {},
   "source": [
    "### Using aisuite"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b587445",
   "metadata": {},
   "source": [
    "### Call the model with tools. Tool call is handled internally."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "0b74257b-8d53-4326-8ea1-d4a7f89c0e57",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "It is expected to rain in San Francisco at 2 PM today, so it might not be the best time for an outdoor picnic. You might want to consider indoor alternatives or plan for another day when the weather is more favorable for outdoor activities. If you have any other plans in mind or need further assistance, feel free to ask!\n"
     ]
    }
   ],
   "source": [
    "from aisuite import Client\n",
    "\n",
    "client = Client()\n",
    "messages = [{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"I live in San Francisco. Can you check for weather \"\n",
    "               \"and plan an outdoor picnic for me at 2pm?\"\n",
    "}]\n",
    "response = client.chat.completions.create(\n",
    "    model=\"openai:gpt-4o\", messages=messages, tools=[will_it_rain], max_turns=2\n",
    ")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba5f0327",
   "metadata": {},
   "source": [
    "### Optionally, continue the conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "b1736dc9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sure! If you'd like to go ahead and plan an outdoor picnic despite the rain, here are a few tips to help you enjoy your experience:\n",
      "\n",
      "1. **Choose a Covered Location**: Try to find a spot with a shelter, like a gazebo or a pavilion, in one of San Francisco's parks. These can provide good protection from the rain.\n",
      "\n",
      "2. **Prepare for Wet Weather**:\n",
      "   - Bring waterproof blankets or tarps to sit on.\n",
      "   - Pack umbrellas and raincoats to stay dry.\n",
      "   - Use waterproof containers and bags to keep your picnic items protected.\n",
      "\n",
      "3. **Select Comforting Foods**: Warm beverages in thermoses and foods that are enjoyable when slightly cooler, such as sandwiches, can be comforting on a rainy day.\n",
      "\n",
      "4. **Stay Safe**: Be cautious of slippery surfaces and keep an eye on kids or pets if they are joining you.\n",
      "\n",
      "5. **Enjoy the Atmosphere**: Rain can create a cozy and calming environment. Embrace the natural sounds and sights of the rain.\n",
      "\n",
      "6. **Plan Indoor Activities**: Bring board games or books in case the rain becomes too heavy.\n",
      "\n",
      "Have fun, and make the most of your unique outdoor picnic experience! If you need more help with planning or have any other questions, let me know.\n"
     ]
    }
   ],
   "source": [
    "messages.extend(response.choices[0].intermediate_messages)\n",
    "messages.append({\n",
    "    \"role\": \"user\", \"content\": \"Schedule it despite the rain\"\n",
    "})\n",
    "response = client.chat.completions.create(\n",
    "    model=\"openai:gpt-4o\", messages=messages)\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bf09c0a",
   "metadata": {},
   "source": [
    "### Using, other providers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "6c266c68-095b-4625-8de5-70960a117f69",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I apologize, but it looks like it will be raining in San Francisco at 2:00 PM today. This might not be the best conditions for an outdoor picnic. However, I can suggest a few alternatives:\n",
      "\n",
      "1. Reschedule: We could check the weather for a different time today or another day this week. Would you like me to check a different time or date?\n",
      "\n",
      "2. Indoor picnic: You could have an indoor picnic at home or find a covered area in a park with picnic shelters.\n",
      "\n",
      "3. Rain-ready picnic: If you're up for an adventure, you could prepare for a rainy day picnic with appropriate gear like umbrellas, waterproof blankets, and covered food containers.\n",
      "\n",
      "4. Alternative activity: We could look into indoor activities or attractions in San Francisco that you might enjoy instead.\n",
      "\n",
      "What would you prefer to do? If you'd like to try for a different time or date, please let me know, and I'll be happy to check the weather again.\n"
     ]
    }
   ],
   "source": [
    "messages = [{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"I live in San Francisco. Can you check for weather \"\n",
    "               \"and plan an outdoor picnic for me at 2pm?\"\n",
    "}]\n",
    "response = client.chat.completions.create(\n",
    "    model=\"anthropic:claude-3-5-sonnet-20240620\", messages=messages, tools=[will_it_rain], max_turns=2\n",
    ")\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25a8c5ab-3a9f-4bf1-8174-aba313a00085",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"groq:llama3-8b-8192\", messages=messages, tools=[will_it_rain], max_turns=2)"
   ]
  },
 {
   "cell_type": "code",
   "execution_count": 17,
   "id": "53e937bd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I can help with that! To provide accurate information, I'll need to know your tolerance for rain. Would you prefer the picnic indoors if it rains?\n"
     ]
    }
   ],
   "source": [
    "response = client.chat.completions.create(\n",
    "    model=\"ollama:llama3-groq-tool-use\", messages=messages, tools=[will_it_rain], max_turns=2)\n",
    "print(response.choices[0].message.content)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
